from types import FunctionType, CodeType
from typing import Callable
from datetime import datetime


def str2func(content: str) -> Callable:
    func = compile(source=content, filename="", mode="exec")  # 将字符串转换为compile对象
    _main = None
    for f in func.co_consts:    # 遍历字符串内存在的所有变量和对象
        if f and isinstance(f, CodeType) and f.co_name and f.co_name == "main":
            _main = FunctionType(f, {"now": datetime.now})
    if not _main:
        raise AttributeError("脚本函数中不存在main函数作为入口")
    return _main
